package model

import (
	"fmt"
	"time"

	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type Team struct {
	ID        uint      `gorm:"primaryKey;autoIncrement" json:"id"`
	CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
	Name      string    `gorm:"size:64;not null;unique;column:name" json:"name"`
	Introduce string    `gorm:"size:255;not null;column:introduce" json:"introduce"`
	// 成员
	Members   []User `gorm:"many2many:team_users;" json:"members"`
	CreatorBy string `gorm:"size:64;not null;column:creator_by" json:"creator_by"`
}

func (t *Team) Create(tx *gorm.DB) error {
	var result *gorm.DB
	if t.ID == 0 {
		result = tx.Create(t)
	} else {
		result = tx.Save(t)
	}

	if result.Error != nil {
		return fmt.Errorf("团队操作失败：%w", result.Error)
	}
	return nil
}

func (t *Team) Delete(tx *gorm.DB, id interface{}) error {
	if err := tx.Delete(&Team{}, id).Error; err != nil {
		return fmt.Errorf("删除团队失败: %w", err)
	}
	return nil
}

func (t *Team) GetByID(tx *gorm.DB, id any) (*Team, error) {
	if err := tx.First(t, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fmt.Errorf("团队未找到: %w", err)
		}
		return nil, fmt.Errorf("获取团队失败: %w", err)
	}
	return t, nil
}

func (t *Team) List(tx *gorm.DB) ([]*Team, error) {
	var teams []*Team
	result := tx.Find(&teams)
	if result.Error != nil || errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("获取团队列表失败")
	}
	return teams, nil
}
